<template>
	<div class="outer">
    <headers @back-click="back()" :headers="headers"></headers>
		<scroll :topArea="44" :bottomArea="94" ref="orderPage" :pullDownRefresh="false" :pullUpLoad="false">
  		<div class="detail-area">
        <div class="detail-content" style="border:none">
            <div class="img-area">
              <img :src="pic" alt="图片">
            </div>
            <div class="content-area">
              <div class="title">{{name}}</div>
              <div class="price">价值： ￥{{(price/100).toFixed(2)}}</div>
              <div class="sku">
                  <div class="sku-item" v-for="c in sku" :key="c.id">{{c.specificationContent}}</div>
              </div>
            </div>
        </div>
      </div>
      <div class="price-section">
        <div class="title" v-if="insurance > 0">
          <div class="left">
            意外保障 <span>(只需首期支付)</span>
          </div>
          <div class="right">￥{{insurance}}</div>
        </div>
        <div class="coupon" @click="chooseCoupon()">
          <div>
            <span></span>
            <span v-if="!coupon.price">该订单您有<i>{{couponList.length}}</i>张可使用优惠券</span>
            <span v-if="coupon.price">现金抵扣券</span>
          </div>
          <div>
            <span style="color:#ff4000;margin-right:10px" v-if="coupon.price">-￥{{(coupon.price/100).toFixed(2)}}</span>
            <i class="fa fa-ellipsis-h fa-lg" style="color:#666"></i>
          </div>
        </div>
        <div class="content">
          <div class="two-sides">
            <div>租赁详情</div>
            <div>￥{{(price/100).toFixed(2)}}X{{termSeled}}{{type=="DAILY"?"天": "月"}}</div>
          </div>
          <div class="price">总租金: ￥{{(price*termSeled/100).toFixed(2)}}</div>
          <div class="price">应付总额： <span class="total-cost">￥{{(totalCost/100).toFixed(2)}}</span></div>
        </div>
      </div>
      <div class="contact-section" :class="{'active': hasContact}">
        <div class="name-line">
          <div class="person">
            <span></span>
            <span>{{addressDefault.name ? addressDefault.name : "姓名"}}</span>
          </div>
          <div class="phone">
            <span></span>
            <span>{{addressDefault.phone ? addressDefault.phone : "手机号码"}}</span>
          </div>
        </div>
        <div class="address-line">
          <div>
            <span></span>
            <span>{{ (addressDefault.provice || addressDefault.city || addressDefault.regoin) ? (addressDefault.provice + addressDefault.city + addressDefault.regoin) : "所在地区: 省/市/区" }}</span>
          </div>
          <div></div>
        </div>
        <div class="address-more">
          {{addressDefault.text ? addressDefault.text : "请输入详细地址" }}
        </div>
        <div class="input-wrapper">
          <input type="text" placeholder="预约备注">
        </div>
      </div>
     
      <div class="hb-section" v-if="isApay"> 
        <div class="title">
          <div class="left-hb">
            <span></span>
            <span class="hb-title">花呗预授权(可选)</span>
            <span>?</span>
          </div>
          <div class="right-hb" @click="chooseHbys()" :class="{'active': isHbused}"></div>
        </div>
        <div class="content">
          <div>需冻结您的额度 = {{(oriPri/100).toFixed(2)}}-{{(price/100).toFixed(2)}}x{{termSeled}}{{type == "DAILY" ? "天" : "月"}}=￥{{( oriPri/100 -price/100*termSeled).toFixed(2)}}</div>
          <div>蚂蚁花呗额度冻结完成后，更有利于提升你的信用评审和订单审核通过率</div>
        </div>
      </div>
  	</scroll>
    <popup v-model="isCoupon" width="100%" :popup-style="popUpStyle">
      <div class="coupon-wrapper">
        <div class="title">蜜宝优惠券</div>
        <div class="coupon-content">
          <div class="coupon-item" v-for="n in couponList" :key="n.id">
            <div class="price">￥{{(n.price/100).toFixed(2)}}</div>
            <div class="content-area">
              <p>{{n.bonusModelName}}</p>
              <p>{{n.bonusModelNote}}</p>
              <p>不可以与店铺优惠券一起使用</p>
            </div>
            <div class="action">
              <div @click="useCoupon(n)" :class="{'active': n.id == couponIndex}"></div>
            </div>
          </div>
        </div>
        <div class="button-region">
          <div class="button" @click="cancelCoupon()">返回</div>
          <div class="button button-confirm" @click="saveCoupon()">确定</div>
        </div>
      </div>
    </popup>
    <div class="button-area">
      <div>点击确认预约代表已同意 <span>《用户租赁及服务协议》</span></div>
      <div class="button button-confirm" @click="confirm()">提交订单</div>
    </div>
	</div>
</template>

<script>
import { Popup} from 'vux'
import {getCoupon,makeOrder} from "@/api/homepage.js"
import apiService from "@/api/homepage.js"
export default {
  name: 'orderPage',
  components: {
    Popup
  },
  data: function(){
  	return {
      headers: {
        title: "确认预约"
      },
  		userInfo: {
        name: "",
        certNo: ""
      },
      popUpStyle: {
        maxHeight: "90%"
      },
      canPost: false,
      isLoading: false,
      passFail: false,
      good: {},
      id: "",
      type: "",
      sku: [],
      oriPri: "",
      cost: "",
      price: "",
      totalCost: "",
      name: "",
      pic: "",
      insurance: "",
      termSeled: "",
      couponList: 0,
      isCoupon: false,
      couponIndex: {},
      temCoupon: "",
      coupon: {},
      addresses: [],
      addressDefault: {},
      hasContact: false,
      isHbused: false,
      isApay: true,
      channelName: "",
      canBrrow: false
  	}
  },
  methods: {
    back: function(){
      this.$router.go(-1);
    },
    coupons: function(){
      let requestPrice =  this.type == "DAILY" ? this.price*this.termSeled : this.price*30;
      requestPrice = parseInt(requestPrice) +  parseInt(this.insurance);
      getCoupon(this.id,requestPrice).then(data => {
        if(data.code == 200){
          this.couponList = data.data;
        }else {
          this.$vux.toast.show({
            text: data.message,
            time: 1000,
            width: 'auto',
            // position: 'middle'
          })
        }
      })
    },
    chooseCoupon: function(){
      if(this.couponList.length ==0){
        this.$vux.toast.show({
          text: '无可用优惠券',
          time: 1000,
          width: 'auto',
          // position: 'middle'
        })
        return;
      }else {
        this.isCoupon = true;
        this.temCoupon = this.coupon;
        this.couponIndex = this.coupon.id;
      }
    },
    useCoupon: function(n){
      this.temCoupon = this.temCoupon.id == n.id ? {} : n;
      this.couponIndex = this.temCoupon.id;
    },
    saveCoupon: function(){
      this.coupon = this.temCoupon;
      this.isCoupon = false;
      this.totalCost = this.price * this.termSeled  + this.insurance -  (this.coupon.price ? parseInt(this.coupon.price) : 0);
      localStorage.coupon = this.coupon.id;
      this.temCoupon = {};
      this.couponIndex = "";
    },
    cancelCoupon: function(){
      this.isCoupon = false;
      this.temCoupon = {};
      this.couponIndex = "";
    },
    userContacts: function(){
      apiService.getContact().then(data => {
        if(data.code == 200){
          this.addresses = data.data;
          let selectedAddress = JSON.parse(sessionStorage.getItem('selectedAddress'));
          if( selectedAddress && selectedAddress.id){
            this.addressDefault = selectedAddress;
            this.hasContact = true;
          }else {
            if(this.addresses.length > 0){
                let hasDefaultAddress = false;
                this.hasContact = true;
                let defaultAddress = {};
                for(let i=0;i<this.addresses.length;i++){
                    if(this.addresses[i].defaulted){
                        hasDefaultAddress = true;
                        defaultAddress = this.addresses[i];
                        break;
                    }
                }
                if(!hasDefaultAddress){
                    this.addressDefault = this.addresses[0];
                }else {
                    this.addressDefault = defaultAddress;
                }
            }else {
                this.addressDefault = {};
                this.hasContact = false;
            }
          }
        }else {
          this.$vux.toast.show({
            text: data.message,
            time: 1000,
            width: 'auto',
            // position: 'middle'
          })
          this.hasContact = false;
        }
      })
    },
    chooseHbys: function(){
      if(this.isHbused == false){
        this.isHbused = true;
      }else {
        this.isHbused = false;
      } 
    },
    makeParams: function(){
      let  param = {};
      for(let i=0;i<this.sku.length-1;i++){
          if(this.sku[i].specification){
              param[this.sku[i].specification] = this.sku[i].specificationContent;
          }
      }
      param.goodsId =this.id;
      param.channel = this.channelName;
      param.authFreeze = this.isHbused;
      param.leaseDay =  this.type == "DAILY" ? this.termSeled : this.termSeled*30 ;
      if(this.coupon){
        param.userBonusId = this.coupon.id;
      }
      if(this.isHbused){
        let backUrl = window.location.href;
        backUrl = backUrl.replace(/orderPage/,'borrowCache/');
        param.returnUrl = backUrl;
      }
      if(this.addresses.length>0){
        param.contact = this.addressDefault.name;
        param.phone = this.addressDefault.phone;
        param.provice = this.addressDefault.provice;
        param.city = this.addressDefault.city;
        param.regoin = this.addressDefault.regoin;
        param.receiveAddress =  this.addressDefault.text
        return param;
      }else {
        this.$vux.toast.show({
          text: "请填写个人信息",
          time: 1000,
          width: 'auto',
            // position: 'middle'
        })
      }
    },
    confirm:  function(){
      if (!this.addressDefault.text) {
          this.$vux.toast.show({
            text: "请输入地址",
            time: 1000,
            width: 'auto',
            // position: 'middle'
          })
          return
      }
      if(this.isHbused){
        let params = this.makeParams();
        localStorage.goodParam = JSON.stringify(params);
        this.$router.push({name:'authorization'});
      }else {
        let params = this.makeParams();
        makeOrder(params).then(data => {
          if(data.code == 200 && !data.data.url){
            this.$router.push({name: "orderResult"})
          }else if(data.code == 200 && data.data.url){
            window.location.href = data.data.url;
          }else {
            this.$vux.toast.show({
              text: data.message,
              time: 1000,
              width: 'auto',
              // position: 'middle'
            })
          }
        })
      }
    }
  },
  mounted: function(){
    this.isApay = /AlipayClient/.test(window.navigator.userAgent);
    this.good=JSON.parse(localStorage.good);
    this.id = this.good.id;
    this.type=this.good.type;
    this.sku = this.good.sku;
    this.oriPri = this.good.oriPri;
    this.cost = this.good.cost;
    this.termSeled = parseInt(this.good.termSeled);
    this.price = this.type == "DAILY" ? this.good.price : this.good.price*30;
    this.totalCost = this.price * this.termSeled  + this.good.insurance;
    this.name = this.good.name;
    this.pic = this.good.imgUrl;
    this.insurance = this.good.insurance;
    this.canBrrow = this.good.canBrrow;
    this.coupons();
    this.userContacts();
  }
}
</script>

<style lang="scss" scoped>
	.outer {
		height: 100%;
    	width: 100%;
    	position: absolute;
	}
  .price-section {
    background: #fff;
    margin-top: 12px;
    padding: 0 16px;
    font-size: 13px;
    color: #333;
    & .title  {
      height: 45px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      & .left {
        &>span {
          color: #999;
          font-size: 10px;
        }
      }
      & .right {
        color: #999;
      }
    }
    & .coupon {
      width: 100%;
      height: 45px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      &>div:first-child {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        &>span:first-child {
          width: 20px;
          height: 20px;
          background: url("../../assets/img/lease/coupon.png") 0 0 no-repeat;
          margin-right: 12px;
          background-size: 100%;
        }
        & i {
          color: #ff4000;
        }
      }
      &>div:last-child {
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }
    }
    & .content {
      width: 100%;
      & .two-sides {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 45px;
      }
      & .price {
        width: 100%;
        height: 29px;
        text-align: right;
        & .total-cost {
          color: #ff4000;
        }
      }
    }
  }
  .contact-section {
    background: #fff;
    margin-top: 12px;
    padding: 0 16px;
    font-size: 13px;
    color: #666;
    &.active {
      color: #333;
    }
    &>div {
      height: 45px;
      display: flex;
      align-items: center;
      &:not(:last-child){
        border-bottom: 1px solid #eee;
      }
    }
    & .name-line {
      justify-content: space-between;
      &>div {
        width: 50%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        &>span:first-child {
          display: inline-block;
          width: 20px;
          height: 20px;
          margin-right: 12px;
          background: url("../../assets/img/lease/user-icon.png") 0 0 no-repeat;
          background-size: 300%;
        }
      }
      & .person {
        &>span:first-child {
          background-position: 13% 13%;
        }
      }
      & .phone {
        &>span:first-child {
          background-position: 86% 13%;
        }
      }
    }
    & .address-line {
      justify-content: space-between;
      &>div {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        &>span:first-child {
          display: inline-block;
          width: 20px;
          height: 20px;
          margin-right: 12px;
          background: url("../../assets/img/lease/user-icon.png") 0 0 no-repeat;
          background-size: 250%;
          background-position: 8% 92%;
        }
        &:first-child {
          width: 98%;
        }
      }
      &>div:last-child {
          background: url("../../assets/img/comm/login_arrow_small@3x.png") 0 0 no-repeat;
          height: 15px;
          width: 15px;
          background-size: 50%;
          background-position: 62% 62%;
      }
    }
    & .address-more {
      padding-left: 32px;
    }
    & .input-wrapper {
      padding-left: 20px;
      &>input {
        width: 100%;
        height: 33px;
        line-height: 33px;
        background: #f5f5f5;
        color: #b8b8b8;
        padding: 0 12px;
        border-radius: 3px;
      }
    }
  }
  .button-area {
    background: #f7f7f7;
    z-index: 300;
    padding: 0 16px;
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    height: 94px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    &>div {
      width: 100%;
      text-align: center;
      &:last-child{
        margin-bottom: 10px;
      }
      &:first-child {
        margin-top: 24px;
        font-size: 12px;
        color: #bbb;
        &>span{
          color: #00b8fd;
        }
      }
    }
  }
  .hb-section {
    background: #fff;
    margin-top: 12px;
    padding: 0 16px;
    font-size: 13px;
    & .title {
      width: 100%;
      height: 45px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      & .left-hb {
        display: flex; 
        justify-content: flex-start;
        align-items: center;
        &>span:first-child {
          background: url('../../assets/img/comm/hb.png') 0 0/100% 100% no-repeat;
          margin-right: 12px;
          width: 20px;
          height: 20px;
        }
        &>span:last-child {
          margin-left: 8px;
          width: 12px;
          height: 12px;
          border-radius: 50%;
          border: 1px solid #69afff;
          color: #69afff;
          text-align: center;
          line-height: 12px;
          font-size: 10px;
        }
      }
      & .right-hb {
        width: 15px;
        height: 15px;
        background: url('../../assets/img/lease/untick-1.png') 0 0/100% 100% no-repeat;
      }
      & .active {
        background: url('../../assets/img/lease/tick-1.png') 0 0/100% 100% no-repeat;
      }
    }
    & .content {
      padding-left: 32px;
      padding-bottom: 15px;
      padding-right: 8px;
      &>div {
        font-size: 12px;
        line-height: 18px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        &:first-child {
          color: #666;
          margin-bottom: 8px;
        }
        &:last-child {
          color: #b8b8b8;
        }
      }
    }
  }
  .coupon-wrapper {
    background: #fff;
    padding: 0 16px;
    padding-bottom: 55px;
    & .title {
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
      border-bottom: 1px solid #eee;
      background: #fff;
    }
    & .coupon-content {
      max-height: 400px;
      overflow-y: scroll;
      overflow-x: hidden;
    }
    & .coupon-item {
      width: 341px;
      height: 84px;
      border: 1px solid #CAE3FF;
      border-radius: 6px;
      background: #F8FBFF;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      & .price {
        width: 82px;
        font-size: 16px;
        color: #999;
        text-align: center;
      }
      & .content-area {
        height: 100%;
        width: 170px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: center;
        &>p {
          height: 20px;
          width: 100%;
          font-size: 12px;
          color: #999;
          line-height: 20px;
          display:block;
          white-space:nowrap;
          overflow:hidden;
          text-overflow:ellipsis;
          &:first-child {
            line-height: 20px;
            height: 20px;
            color: #666;
            font-size: 14px;
          }
        }
      }
      & .action {
        width: 80px;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        & div {
          width: 15px;
          height: 15px;
          background: url("../../assets/img/lease/untick-1.png") 0 0 no-repeat;
          background-size: 100%;
          &.active {
            background: url("../../assets/img/lease/tick-1.png") 0 0 no-repeat;
            background-size: 100%;
          }
        }
      }
    }
    & .button-region {
      padding: 0 16px;
      background: #fff;
      position: fixed;
      right: 0;
      left: 0;
      bottom: 0;
      height: 55px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
</style>